﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using AgriculturalMachinery.Models;

namespace AgriculturalMachinery.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        AccountRepository amr = new AccountRepository();

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "登录失败！用户名或密码错误码？");
                }

                //AgriMachineRepository amr = new AgriMachineRepository();
                //Clients client = amr.FindUserByEmail(model.UserName);
                //Response.Write("successful");
                //string uname = Request.Params["username"];
                //string pwd = Request.Params["password"];

                return RedirectToAction("Index", "Home");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();
            // 设置cookie超时时间, 写成一行只要改一个数字就行了
            Response.Cookies["cooUserName"].Expires = Response.Cookies["cooUserID"].Expires = Response.Cookies["cooAvatar"].Expires = DateTime.Now.AddDays(-1);
            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                // MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                //if (createStatus == MembershipCreateStatus.Success)
                //{
                //    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                //    return RedirectToAction("Index", "Home");
                //}
                //else
                //{
                //    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                //}
                // Response.Write("<script type='text/javascript'>alert('aaaa');location.href='/Account/Register'</script>");

                string uName = model.UserName.Trim();
                // 创建用户
                Clients tempClient = new Clients();

                tempClient.UserName = uName;
                tempClient.Contact = model.Contact.Trim();
                tempClient.Email = model.Email.Trim();
                tempClient.Password = model.Password.Trim();
                tempClient.RegDate = DateTime.Now;
                // 默认头像
                tempClient.Avatar = "defaultAvatar.png";
                tempClient.IsValid = 0;

                amr.AddUser(tempClient);

                // 创建cookie
                // ViewData["loginedUser"] = client;
                Response.Cookies["cooUserName"].Value = uName;
                // 设置cookie超时时间
                Response.Cookies["cooUserName"].Expires = DateTime.Now.AddMinutes(20);

                Response.Cookies["cooUserID"].Value = tempClient.UserID.ToString();
                Response.Cookies["cooUserID"].Expires = DateTime.Now.AddMinutes(20);

                Response.Cookies["cooAvatar"].Value = "defaultAvatar.png";
                Response.Cookies["cooAvatar"].Expires = DateTime.Now.AddMinutes(20);

                Response.Write(uName + ":" + "defaultAvatar.png");
                return RedirectToAction("Index", "Home");
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        [HttpPost]
        public void MyLogOn(LogOnModel model, string returnUrl)
        {
            //if (ModelState.IsValid)

            string email = Request.Params["email"];
            string pwd = Request.Params["password"];
            try
            {
                Clients client = amr.FindUserByEmail(email);

                if (!pwd.Equals(client.Password))
                {
                    Response.Write("密码错误");
                    return;
                }
                // ViewData["loginedUser"] = client;
                Response.Cookies["cooUserName"].Value = client.UserName;
                // 设置cookie超时时间
                Response.Cookies["cooUserName"].Expires = DateTime.Now.AddMinutes(20);

                Response.Cookies["cooUserID"].Value = client.UserID.ToString();
                Response.Cookies["cooUserID"].Expires = DateTime.Now.AddMinutes(20);

                Response.Cookies["cooAvatar"].Value = client.Avatar;
                Response.Cookies["cooAvatar"].Expires = DateTime.Now.AddMinutes(20);


                Response.Write(client.UserName + ":" + client.Avatar);
            }
            catch
            {
                Response.Write("登录失败");
            }
        }

        [HttpPost]
        public void MyRegister(RegisterModel model)
        {
            // return RedirectToAction("Register");
        }

        //
        // Get
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult index(int? page)
        {
            AccountRepository ar = new AccountRepository();
            var AllClients = ar.FindAllClients();
            var PagedAllClients = new AccountViewModel<Clients>(AllClients,
                page ?? 0,
                7);
            return View(PagedAllClients);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Delete(int id)
        {
            AccountRepository ar = new AccountRepository();
            ar.DeleteUser(id);
            return RedirectToAction("index");
        }

        // jquery 发来的批量删除函数
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete()
        {
            string[] delString = Request.Params["delString"].Split('|');
            AccountRepository ar = new AccountRepository();
            for (int i = 0; i < delString.Length; i++)
            {
                ar.DeleteUser(Convert.ToInt32(delString[i]));
            }
            return RedirectToAction("index");
        }

        // 添加用户
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddUser()
        {
            string UserName = Request.Params["UserName"];
            string Contact = Request.Params["Contact"];
            string Email = Request.Params["Email"];
            string Password = Request.Params["Password"];
            string RegDate = Request.Params["RegDate"];
            Clients c = new Clients();

            c.UserName = UserName;
            c.Contact = Contact;
            c.Email = Email;
            c.Password = Password;
            c.RegDate = Convert.ToDateTime(RegDate);
            c.Avatar = "defaultAvatar.png";
            c.IsValid = 0;

            AccountRepository ar = new AccountRepository();
            ar.AddUser(c);

            return RedirectToAction("index");
        }

    }
}
